<template>
  <div class="app-container">
    <div class="filter-container">
      <span>{{ $t("DailyDataSummary.channel") }}:&nbsp;</span>
      <el-select
        v-model="channelId"
        style="width: 140px"
        class="filter-item"
        @change="changeChannel"
      >
        <el-option
          v-for="item in channelListOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <span>{{ $t("DailyDataSummary.serverlist") }}:&nbsp;</span>
      <el-select
        v-model="channelId"
        style="width: 140px"
        class="filter-item"
        @change="changeChannel"
      >
        <el-option
          v-for="item in channelListOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        :label="$t('demo_excel.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="105px"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.time')"
        width="180px"
        align="center"
        prop="time"
        sortable="custom"
      >
        <template slot-scope="{ row }">
          <!-- <span> {{ row.time }}</span> -->
          <span> {{ getShowTime(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.title')"
        width="180px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.title
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.author')"
        width="180px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.importance')"
        width="105px"
        align="center"
      >
        <template slot-scope="{ row }">
          <svg-icon
            v-for="n in +row.importance"
            :key="n"
            name="star"
            class="meta-item__icon"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.readings')"
        align="center"
        width="95"
      >
        <template slot-scope="{ row }">
          <span v-if="row.readings">{{ row.readings }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.status')"
        class-name="status-col"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag :type="el_tag_type_config[row.status]">
            {{ statusConfig[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('demo_excel.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t("table.edit") }}
          </el-button>
          <el-button
            v-if="row.status == 2"
            size="mini"
            type="success"
            @click="handleModifyStatus(row, 'published')"
          >
            {{ $t("table.publish") }}
          </el-button>
          <el-button
            v-if="row.status == 1"
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            {{ $t("table.draft") }}
          </el-button>
          <el-button
            v-if="row.status !== 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t("table.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempShowData"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('table.date')" prop="time">
          <el-date-picker
            v-model="tempShowData.time"
            type="datetime"
            placeholder="Please pick a date"
          />
        </el-form-item>
        <el-form-item :label="$t('table.title')" prop="title">
          <el-input v-model="tempShowData.title" />
        </el-form-item>
        <el-form-item :label="$t('table.status')">
          <el-select
            v-model="tempShowData.status"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.importance')">
          <el-rate
            v-model="tempShowData.importance"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="3"
            style="margin-top: 8px"
          />
        </el-form-item>
        <el-form-item :label="$t('table.remark')">
          <el-input
            v-model="tempShowData.abstractContent"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
//每日数据汇总
import { createArticle } from "@/api/articles";
import Pagination from "@/components/Pagination/index.vue";
import { DemoExcel } from "@/store/model/DemoExcel";
import { formatJson } from "@/utils";
import { DateUtil } from "@/utils/DateUtil";
import { exportJson2Excel } from "@/utils/excel";
import { Logger } from "@/utils/Logger";
import { Form } from "element-ui";
import { Component, Vue } from "vue-property-decorator";

const calendarTypeOptions = [
  { key: "CN", displayName: "China" },
  { key: "US", displayName: "USA" },
  { key: "JP", displayName: "Japan" },
  { key: "EU", displayName: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce(
  (acc: { [key: string]: string }, cur) => {
    acc[cur.key] = cur.displayName;
    return acc;
  },
  {}
) as { [key: string]: string };

@Component({
  name: "DailyDataSummary",
  components: {
    Pagination,
  },
  filters: {
    typeFilter: (type: string) => {
      return calendarTypeKeyValue[type];
    },
  },
})
export default class extends Vue {
  private tableKey = 0;
  private list: DemoExcel[] = [];
  private total = 0;
  private listLoading = true;

  private channelListOptions = [
  
  ];
  private channelId: number = 0

  //列表查询选项
  private listQuery = {
    page: 1, //第几页
    limit: 20, //一页多少个
    importance: undefined, //重要程度
    title: undefined, //标题
    type: undefined, //类型
    sort: "+id", //排序方式
  };

  private importanceOptions = [1, 2, 3];
  private calendarTypeOptions = calendarTypeOptions;
  private el_tag_type_config: Array<string> = [
    "",
    "success",
    "info",
    "warning",
    "danger",
  ];
  private statusConfig = ["default", "published", "draft", "delete"];
  private sortOptions = [
    { label: "ID Ascending", key: "+id" },
    { label: "ID Descending", key: "-id" },
  ];

  private statusOptions = ["published", "draft", "deleted"];
  private showReviewer = false;
  private dialogFormVisible = false; //dialog是否显示
  private dialogStatus = ""; //dialog状态，更新或者新创建
  private textMap = {
    update: "Edit",
    create: "Create",
  };

  private rules = {
    timestamp: [
      { required: true, message: "timestamp is required", trigger: "change" },
    ],
    title: [{ required: true, message: "title is required", trigger: "blur" }],
  };

  private downloadLoading = false;
  private tempShowData: DemoExcel = new DemoExcel();

  created() {
    this.getList();
  }

  private getShowTime(model: DemoExcel) {
    return DateUtil.formatDateStr(model.time);
  }

  private changeChannel() {
    Logger.log("changeChannel=====", this.channelId);
  }

  private async getList() {
    this.listLoading = true;
    this.list = DemoExcel.getShowList(this.listQuery);
    Logger.log("getList===", this.listQuery, this.list);
    this.total = DemoExcel.totalNum;
    setTimeout(() => {
      this.listLoading = false;
    }, 0.5 * 1000);
  }

  private handleModifyStatus(row: any, status: string) {
    this.$message({
      message: "操作成功",
      type: "success",
    });
    row.status = status;
  }

  private sortChange(data: any) {
    const { prop, order } = data;
    Logger.log("sortChange===", data);
    this.listQuery.page = 1;
    if (prop === "id") {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.getList();
    } else if (prop == "time") {
      if (order === "ascending") {
        this.listQuery.sort = "+time";
      } else {
        this.listQuery.sort = "-time";
      }
      this.getList();
    }
  }

  private resetTempArticleData() {
    // this.tempShowData = cloneDeep(defaultArticleData);
  }

  private handleCreate() {
    this.resetTempArticleData();
    this.dialogStatus = "create";
    this.dialogFormVisible = true;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }

  private createData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        const articleData = this.tempShowData;
        articleData.id = Math.round(Math.random() * 100) + 1024; // mock a id
        articleData.author = "vue-typescript-admin";
        const { data } = await createArticle({ article: articleData });
        data.article.timestamp = Date.parse(data.article.timestamp);
        this.list.unshift(data.article);
        this.dialogFormVisible = false;
        this.$notify({
          title: "成功",
          message: "创建成功",
          type: "success",
          duration: 2000,
        });
      }
    });
  }

  private handleUpdate(row: any) {
    this.tempShowData = Object.assign({}, row);
    Logger.log("handleUpdate==", row, this.tempShowData);
    this.dialogStatus = "update";
    this.dialogFormVisible = true;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate(); // 移除所有表单项的校验
    });
  }

  private updateData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        Logger.log("tempShowData===", this.tempShowData);
        DemoExcel.updateModel(this.tempShowData);
        this.dialogFormVisible = false;
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 2000,
        });
      }
    });
  }

  private handleDelete(row: any, index: number) {
    this.$notify({
      title: "Success",
      message: "Delete Successfully",
      type: "success",
      duration: 2000,
    });
    this.list.splice(index, 1);
  }

  private handleDownload() {
    this.downloadLoading = true;
    const tHeader = ["id", "time", "title", "status", "importance", "author"];
    const data = formatJson(tHeader, this.list);
    Logger.log("handleDownload====", this.list, data);
    exportJson2Excel(tHeader, data, "demo_excel");
    this.downloadLoading = false;
  }
}
</script>
